package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.domain.IpLog;
import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.exception.CustomerException;
import cn.wolfcode.p2p.base.mapper.LoginInfoMapper;
import cn.wolfcode.p2p.base.service.IAccountService;
import cn.wolfcode.p2p.base.service.ILoginInfoService;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.base.vo.VerifyCodeVO;
import cn.wolfcode.p2p.hosting.service.IHostingService;
import cn.wolfcode.p2p.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class LoginInfoServiceImpl implements ILoginInfoService {
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private IAccountService accountService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IHostingService hostingService;

    /**
     * 用户注册
     */
    @Override
    public void register(String username, String verifycode, String password, String confirmPwd) {
        //验证前台表单传过来的数据
        AssertUtil.instance().isLength(username, Constants.LENGTH_PHONE, "手机号格式不正确")
                .isMobile(username, "手机号格式不正确")
                .isRangeLength(password, Constants.MIN_LENGTH_PASSWORD, Constants.MAX_LENGTH_PASSWORD,
                        "密码长度" + Constants.MIN_LENGTH_PASSWORD + "-" + Constants.MAX_LENGTH_PASSWORD + "位")
                .isEquals(password, confirmPwd, "两次输入密码不一致")
                .isLength(verifycode, Constants.LENGTH_VERIFYCODE, "验证码格式无效")
                .isFalse(existUsername(username), "手机号已被注册");

        //获取发送验证码手机号
        VerifyCodeVO vo = UserContext.getVerifyCodeVO();
        AssertUtil.instance().isNotNull(vo, "请重新发送验证码");
        String lastPhone = vo.getPhone();

        //判断手机号与发送手机号是否一致
        AssertUtil.instance().isEquals(lastPhone, username, "注册的手机号与发送验证码的手机号不一致");

        //验证码过期校验
        Date lastTime = vo.getSendTime();
        Date now = new Date();
        AssertUtil.instance().isFalse(DateUtil.getSecondsBetween(lastTime, now)
                > Constants.VERIFYCODE_VALID_SECOND, "验证码已失效,请重新发送")
                .isEquals(verifycode, vo.getCode(), "无效的验证码");

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUsername(username);
        loginInfo.setPassword(MD5.encode(password + username));
        loginInfo.setUserType(LoginInfo.USERTYPE_WEB);
        loginInfoMapper.insert(loginInfo);

        //注册成功,初始化account
        accountService.init(loginInfo);
        //注册成功,初始化userinfo
        userInfoService.init(loginInfo);

        //同步一个托管平台的账户
        hostingService.createAccount(loginInfo);

        //绑定手机号
        hostingService.bindPhone(loginInfo);
    }

    @Override
    public boolean existUsername(String username) {
        AssertUtil.instance().isLength(username, Constants.LENGTH_PHONE, "手机号格式不正确")
                .isMobile(username, "手机号格式不正确");
        return loginInfoMapper.selectByUsername(username) > 0;
    }

    @Override
    public void login(LoginInfo loginInfo, Integer userType) {
        //前台校验手机号,后台不需要检验手机号
        if (userType == IpLog.USERTYPE_WEB) {
            //账号密码的校验
            AssertUtil.instance().isLength(loginInfo.getUsername(), Constants.LENGTH_PHONE, "手机号格式不正确")
                    .isMobile(loginInfo.getUsername(), "手机号格式不正确");

        } else {
            AssertUtil.instance().isFalse(!StringUtils.hasLength(loginInfo.getUsername()), "用户不存在");
        }
        //都要判断密码
        AssertUtil.instance().isRangeLength(loginInfo.getPassword(), Constants.MIN_LENGTH_PASSWORD, Constants.MAX_LENGTH_PASSWORD,
                "密码长度" + Constants.MIN_LENGTH_PASSWORD + "-" + Constants.MAX_LENGTH_PASSWORD + "位");


        //判断用户是否存在
        LoginInfo temp = loginInfoMapper.selectByUsernameAndPassword(loginInfo.getUsername(), MD5.encode(loginInfo.getPassword() + loginInfo.getUsername()));

        if (temp == null) {
            throw new CustomerException("账户或密码错误,请重新输入");
        }
        //校验用户状态
        AssertUtil.instance().isFalse(temp.getState() == LoginInfo.STATE_LOCK, "账户已被锁定,请联系客服");

        //放入session中
        UserContext.setCurrentUser(temp);

    }

    @Override
    public List<LoginInfo> listAuditors() {
        return loginInfoMapper.listAuditors();
    }

    @Override
    public void logout() {
        UserContext.getSession().invalidate();
    }
}
